<?php

class OauthController extends Controller {

	public function loginAction() {
		$type = strtolower(Request::get('type'));
		$code = Request::get('code');
		$openid = Request::get('openid');
		$access_token = Request::get('access_token');
		if (!in_array($type, ['qq', 'weibo', 'weixin', 'miniwx'])) {
			Response::ajax(NORMAL_ERROR, '类型有误,登录失败');
		}
		if ($type == 'qq') {

		} elseif ($type == 'weibo') {

		} elseif ($type == 'weixin') {

		} elseif ($type == 'miniwx') {
			$mini = new WeMini\Crypt(Configure::get('weixin'));
			try {
				$result = $mini->session($code);
				if (isset($result['errcode']) && $result['errcode']) {
					Response::ajax(NORMAL_ERROR, $result['errcode'] . ':' . $result['errmsg']);
				}
				if (isset($result['openid']) && $result['openid']) {
					if ($thirdUserInfo = self::model('user_oauth')->getOne('openid=? and oauth_id=?', [$result['openid'], user_oauthModel::MINIWX])) {
						self::model('user_oauth')->update([
							'access_token' => $result['session_key'],
						], 'id=?', $thirdUserInfo['id']);
						if ($thirdUserInfo['uid']) {
							$userInfo = self::model('user')->getOne('uid=?', $thirdUserInfo['uid']);
							if ($userInfo['nickname']) {
								$userInfo['ticket'] = self::model('user')->login($userInfo);
								Response::ajax(200, 'success', userModel::buildBaseUserInfo($userInfo));
							}
						}
					} else {
						$thirdUserInfo = [
							'oauth_id' => user_oauthModel::MINIWX,
							'openid' => $result['openid'],
							'add_time' => date('Y-m-d H:i:s'),
							'birthday' => '1970-01-01',
							'access_token' => $result['session_key'],
						];
						if (!$thirdUserInfo['id'] = self::model('user_oauth')->insert($thirdUserInfo, true)) {
							Response::ajax(SYSTEM_ERROR, '第三方绑定信息获取失败,请稍后重试');
						}
					}
					Response::ajax(USER_NO_BIND, '账号未绑定', ['verifyToken' => self::model('user')->encodeVerifyToken($thirdUserInfo)]);
				}
			} catch (Exception $ex) {
				Log::write('获取用户信息异常:' . json_encode($result, 320), 'WARN');
			}
//            print_r($mini->session($code));
			//print_r($mini->decode($iv, $sessionKey, $decode));
			////print_r($mini->userInfo($code, $iv, $decode));
		}
		Response::ajax(SYSTEM_ERROR, '获取用户信息失败,请稍后重试');
	}

	public function registerAction() {
		$encryptedData = isset($_POST['encryptedData']) ? $_POST['encryptedData'] : '';
		$iv = isset($_POST['iv']) ? $_POST['iv'] : '';
		$verifyToken = Request::getParams('verifyToken');
		$mini = new WeMini\Crypt(Configure::get('weixin'));
		$verifyInfo = self::model('user')->decodeVerifyToken($verifyToken);
		if (!$verifyInfo || !$verifyInfo['id']) {
			Response::ajax(NORMAL_ERROR, '校验码失效,请重新获取');
		}
		$oauthInfo = self::model('user_oauth')->getOne('id=?', $verifyInfo['id']);
		if (!$oauthInfo) {
			Response::ajax(NORMAL_ERROR, '第三方信息校验失败,请重新登录');
		}
		try {
			$result = $mini->decode($iv, $oauthInfo['access_token'], $encryptedData);
			if (isset($result['openId']) && $result['openId']) {
				//登录成功
				$userInfo = self::model('user')->getOne('uid=?', $oauthInfo['uid']);
				if (!$userInfo) {
					$uid = self::model('user')->insert([
						'openid' => $result['openId'],
						'nickname' => $result['nickName'],
						'sex' => $result['gender'],
						'avatar' => $result['avatarUrl'],
						'type' => 1,
						'add_time' => date('Y-m-d H:i:s'),
					], true);
					$userInfo = self::model('user')->getOne('uid=?', $uid);
				}
				if (!self::model('user_oauth')->update([
					'openid' => $result['openId'],
					'nickname' => $result['nickName'],
					'sex' => $result['gender'],
					'avatar' => $result['avatarUrl'],
					'uid' => $userInfo['uid'],
				], 'id=?', $verifyInfo['id'])) {
					Response::ajax(SYSTEM_ERROR, '用户信息更新失败,请重新登录');
				}
				if (self::model('user')->getOne('nickname=?', $result['nickName'])) {
					$result['nickName'] = uniqid();
				}
				Response::ajax(200, 'success', self::model('user')->getLoginInfo($userInfo));
			}
		} catch (Exception $exc) {
			Log::write('校验微信用户信息失败:' . $exc->getTraceAsString(), 'WARN');
		}
		Response::ajax(SYSTEM_ERROR, '信息获取失败,请稍后重试');
	}
}
